<template>
  <div id="ForeChat">
    <el-row>
      <el-col :span="2" class="visible-none"></el-col>

      <!-- 在线列表 -->
      <el-col :span="6">
        <div class="grid-content bg-purple">
          <div class="cr-personList">
            <el-container>
              <el-header>在线列表</el-header>
              <el-main style="padding:0;">
                <!-- v-for -->
                <div :class="{'cr-each':true,'background-f3f4f5':chatActive == index}" v-for="(user,index) in users"
                     :key="user.username"
                     @click="changeChatUser(user.username,index)"
                >
                  <div>
                    <span>
                     <el-avatar :size="50" src="https://p3-passport.byteimg.com/img/user-avatar/54e826e7ede327c5a02fb8f6f5cd9f30~100x100.awebp"/>
                    </span>
                    {{ user.username }}
                  </div>
                  <div>{{ user.onlineActive?user.chatTime:'离线' }}</div>
                </div>
<!--                <div class="cr-each" v-else>卖火柴的小女孩</div>-->
              </el-main>
            </el-container>
          </div>
        </div>
      </el-col>


      <!--      内容中间部分-->
      <el-col :span="14" style="background-color: white">
          <div class="rm-con">
            <el-container>
                <el-header>
                  {{ chatUser }}
                </el-header>
                <el-main>
                  <div class="rm-main">
                        <div v-for="(item,index) in content" :key="index">
                          <p style="float:left" v-if="item.from == chatUser">
                            <el-icon :size="20" ><avatar /></el-icon>
                            <span>{{ item.text }}</span>
                          </p>

                          <p style="clear:both" ></p>

                          <p  style="float:right" v-if="item.from == currentUser">
                            <span>{{item.text}}</span>
                            <el-icon :size="20" ><avatar /></el-icon>
                          </p>

                          <p style="clear:both" ></p>

                        </div>
                  </div>
                </el-main>
                <el-footer>
                    <el-row style="padding:0;margin:0;">
                        <el-col :span="24">
                            <div class="grid-content bg-purple footer-send">
                                <textarea autofocus v-model="text" @keyup.enter="sendMessage"/>
                            </div>
                        </el-col>
                      <div class="enter-send" @click="sendMessage">按 Enter 发送消息</div>
                    </el-row>
                </el-footer>
            </el-container>
          </div>
      </el-col>

      <el-col :span="2" class="visible-none"></el-col>
    </el-row>
  </div>
</template>

<script>
import request from "@/utils/request";
import {getConcernList} from '@/api/blog/user'
import {Promotion,Avatar} from "@element-plus/icons-vue"
import {uplistOne} from '@/utils/tool/array.js'
let socket;

export default {
  name: "ChatRoom",

  components:{
      Avatar
  },

  setup(){
    return{
      Promotion
    }
  },

  data(){
    return{
      users: [],
      chatUser: '',
      currentUser:'own',
      text: "",
      content: [],
      message:'',
      tmpMessage:'',
      chatActive:-1,
      charType:this.$route.query.charType,
      concernList:[],
      socket:{},
      socketUrl:'',
    }
  },
  created() {
    this.load()
    this.chatUser = history.state.username || ''
  },

  mounted(){
    // this.load()
    // console.log("username",this.$route);
    // console.log("username",history.state.username);
  },

  props:{
    // charType:{
    //   type:String,
    //   default:''
    // }
  },
  // destroy(){
  //   this.socket.close();
  //   this.socket = null;
  // },

  beforeRouteLeave(to,from,next){
    // debugger
    this.socket.close();
    this.socket = null;
    next();
  },

  methods: {
    changeChatUser(username,index){
      this.chatUser = username
      this.chatActive = index
      // console.log(`--- 聊天消息----------------------------------------`,this.content)
    },
    sendMessage(){
      if (this.chatUser === "") {
        this.$message({type: 'warning', message: "请选择聊天对象"})
        return;
      }
      if (!this.text) {
        this.$message({type: 'warning', message: "请输入内容"})
      }else{
        this.message = {
          from:this.currentUser,
          to:this.chatUser,
          text:this.text
        }
        this.socket.send(JSON.stringify(this.message));

        this.tmpMessage = {
          from:this.currentUser,
          to:this.chatUser,
          text:this.text
        }
        this.content.push(this.tmpMessage)
        this.text = ''
      }

    },
    getInlineList(data){
      //获取聊天列表
      if(data.users){
        this.users = data.users.filter(user=>user.username != this.currentUser);
        this.users = this.users.map(user=>{
          user.chatTime = (new Date().getHours() + ":" + new Date().getMinutes())
          user.onlineActive = true
          return user
        });
      }
    },
    getConcernList(resolve){
      // console.log("===========getConcernList===========")
      getConcernList({
        userId:this.curUserId
      }).then((res)=>{
        this.concernList =  res.data.map(lis=>{
          lis.chatTime = (new Date().getHours() + ":" + new Date().getMinutes())
          lis.onlineActive = false;
          return lis
        });
        resolve();
        // console.log("====================",this.concernList)
      })
    },
    mapConcernList(data){
      let users = data.users;
      if(users){
        // console.log("--------------有在线列表------------------")
        //有在线列表
        users = data.users.filter(user=>user.username != this.currentUser);
        if(users.length == 0){
          this.users = this.concernList.map(lis=>{
            lis.onlineActive = false
            return lis
          });
          // console.log("222",this.concernList)
          return
        }
        let usernames = users.map(user=>user.username)
        this.users = this.concernList.map(lis=>{
          lis.onlineActive = usernames.includes(lis.username)?true:false
          return lis
        });
      }
      // else{
      //   console.log("--------------无在线列表------------------")
      //   //无在线列表
      //   this.users = this.concernList.map(lis=>{
      //     lis.onlineActive = false
      //     return lis
      //   });
      // }
    },
    handleMessage(data){
      //处理消息
      if(data.from){
        this.content.push(data)
        // console.log(`--- 聊天消息2----------------------------------------`,this.content)
      }
    },
    showChatList(){

    },
    getCacheMessage(data){
      // console.log("====================data.messages===",data.messages)
      if(data.messages){
        this.content = this.content.concat(data.messages);
      }
    },
    load(){
      // console.log("---------------------1111---------------------------")
      this.currentUser = sessionStorage.getItem("user") ? JSON.parse(sessionStorage.getItem("user")) : {}
      this.curUserId = sessionStorage.getItem("userId") ? JSON.parse(sessionStorage.getItem("userId")) : {}
      let username = this.currentUser;
      // this.currentUser = this.currentUser.username
      let socketUrl = `ws://${process.env.VUE_APP_BASE_BLOG_IP}/chatroomserver/${username}`;

      if (this.socket != null) {
        // this.socket.close();
        this.socket = null;
      }
      this.socket =  new WebSocket(socketUrl);

      this.socket.onopen=()=>{
          console.log("websocket已打开");
      }

      this.socket.onmessage=async (msg)=>{
        console.log("=============onmessage====================")
        let data = JSON.parse(msg.data)
        // console.log("=============消息==============",data)
        //获取关注列表
        if(this.charType != 'all'){
          new Promise((resolve,reject)=>{
            this.getConcernList(resolve);
          }).then((pData)=>{
            this.mapConcernList(data);
          });
        }else {
          this.getInlineList(data);
        }
        //接收缓存消息
        this.getCacheMessage(data);

        //处理消息
        this.handleMessage(data)
      },

      this.socket.onerror=()=>{
          console.log("websocket发生了错误");
      }

      this.socket.onclose=()=>{
          console.log("websocket已关闭");
      }
    }
  }
}
</script>

<style lang="less" scoped>
    @import '../../style/ChatRoom.less';
</style>
